import axios, {AxiosInstance} from "axios";

// export const webViewBaseUrl = "http://118.25.141.195:3000";
// export let baseUrl = "http://118.25.141.195:8089/youquan"; //测试
// export const webViewBaseUrl = "https://www.h5.alinlearn.cn:3000";
// let baseUrl = "https://www.h5.alinlearn.cn/service/youquan"; //线上

interface HttpProps {
    url: string;
    method?: "POST" | "GET";
    data?: any;
    token?: string;
}

export interface ResProps {
    success?: boolean;
    data?: any;
}

export let baseUrl = "/service/youquan"; //生产

if (process.env.NODE_ENV !== "production") {
    //  开发 youquan   api生产
    //baseUrl = "/youquan";
    baseUrl = "/api";
}

const request: AxiosInstance = axios.create({
    baseURL: baseUrl,
});

// 添加请求拦截器
request.interceptors.request.use(
    function (config) {
        // 在发送请求之前做些什么
        return config;
    },
    function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
axios.interceptors.response.use(
    function (response) {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        return response;
    },
    function (error) {
        // 超出 2xx 范围的状态码都会触发该函数。
        // 对响应错误做点什么
        return Promise.reject(error);
    }
);

const http = ({url = "", method = "POST", data = {}, token = ""}: HttpProps) =>
    new Promise((resolve: CallableFunction, reject: CallableFunction) => {
        request({
            url,
            method,
            data,
            headers: {
                authorize_token: token || "",
            },
        })
            .then((res: any) => {
                const data: ResProps = res.data;
                if (data.success) {
                    resolve(data);
                } else {
                    reject(data);
                }
            })
            .catch(err => {
                reject(err);
            });
    });

export default http;
